import axios from 'axios'
// import qs from 'qs'
import { Message, Loading } from 'element-ui' 
import router from '../router'
import { md5 } from '../md5/md5'
// 创建axios实例
const baseURL = process.env.Base_Url;
// const baseURL = 'http://192.168.0.151:9999/'

var headerSign = ''
const service = axios.create({
    baseURL: baseURL,
    timeout: 15000 // 请求超时时间
}) 
let bool = false;
var userInfo = {};
service.interceptors.request.use(config => {
    let timestamp = parseInt(new Date().getTime() / 1000);
    headerSign = md5(getheaderSign(config.url, config.data,timestamp)).toUpperCase();
    // if (localStorage.cp_userInfo) {
    //     try {
    //         userInfo = JSON.parse(localStorage.cp_userInfo);
    //     } catch (err) {
    //         userInfo = {};
    //     }
    // }
    config.headers["X-source"] = 'web';
    config.headers["X-timestamp"] = timestamp;
    config.headers["X-version"] = '1.0';
    config.headers["Content-Type"] = 'application/json';
    config.headers["X-sign"] = headerSign;
    config.headers.Authorization = (localStorage.cp_userInfo && JSON.parse(localStorage.cp_userInfo).jwt) || '';
    return config
},error => {
    Message({
        message: "系统错误，请联系管理员！",
        type: 'error',
        duration: 3 * 1000
    })
    return Promise.resolve(error)
}

)
service.interceptors.response.use(
    function (response) {
        //请求正常则返回
        return Promise.resolve(response)
    },
    function (error) {
        return Promise.reject(error)
    }
);
export function baseFetchData (url, params, method) {
    return new Promise((resolve, reject) => {
        service[method](url, params)
            .then(response => {
                let res = response.data;
                if (res.resultCode == 0) {
                    resolve(res);
                }
                else if (res.resultCode == 1001 || res.resultCode == 1100 || res.resultCode == 1006) {
                    if(bool){
                        return
                    }else{
                        bool = !bool;
                    } 
                    Message({
                        message: "您暂未登录,请您先登录",
                        type: 'error',
                        duration: 2 * 1000
                    })
                    sessionStorage.storeUrl = window.location.href;
                    router.push('/login');
                    setTimeout(()=>{
                        bool = false;
                    },3000)
                    return 
                }
                else {
                    if (url == "/sitecount/v1/visit") { return }
                    // Message({
                    //     message: "res.description",
                    //     type: 'error',
                    //     duration: 3 * 1000
                    // })
                    reject(res.description);
                }
            }, err => {
                reject('网络链接失败,请稍候再试...');
            })
            .catch((error) => {
                reject('网络链接失败,请稍候再试...')
            })
    });
}



export function getParam(params) {
    var keys = [];
    var paramList = [];
    for (var key in params) {
      if((!params[key] && params[key]!==0)|| typeof( params[key]) == "object"){
        continue ;
      }
      keys.push(key);
    }
    keys = keys.sort(); //排序
    for (var i = 0; i < keys.length; i++) {
      var tempKey = keys[i];
      if(params[tempKey] === 0){ params[tempKey] ="0"}
      params[tempKey] = params[tempKey] ? params[tempKey] : "";
      paramList.push(tempKey + '=' + params[tempKey]);
    }
    return paramList.join('&');
  }
 
export function getheaderSign (url, body,timestamp) { 
    var params = {
        'X-source': 'web',
        'X-timestamp': timestamp,
        'X-version': '1.0'
    };
    var userInfo = {};
    if (localStorage.cp_userInfo) {
        try {
            userInfo = JSON.parse(localStorage.cp_userInfo);
        } catch (err) {
            userInfo = {};
        }
    }
    if (userInfo.jwt) {
        params.Authorization = userInfo.jwt;
    }
    var lg = getParam(params);
    var sign = url + "?" + lg + "&X-apiKey=e1e499e5746f90191ec5261947055e0c";
    
    if (JSON.stringify(body) !== '{}') {
        body = getParam(body);
        if(!body){
            return sign
        }
        sign += "&bodySign=" + md5(body).toUpperCase();
    } 
    console.log(sign)
    return sign;
}


export function fetchData (url, params, method, callback, failure) {
    baseFetchData(url, params, method).then(res => {
        if (callback != undefined && callback != null) {
            callback(res)
        }
    }, error => {
        // Toast(error);
        if (failure != undefined && failure != null) {
            failure(error)
        } else {
            if (error && error != '') {
                Message({
                    message: error,
                    type: 'error',
                    duration: 3 * 1000
                })
            }
        }
    });
}

//上传文件
export function uploadFile(url,params,callback){ 
    let timestamp = parseInt(new Date().getTime() / 1000);
    var forms = new FormData();
    const headerSign = md5(getheaderSign(url, {},timestamp)).toUpperCase();
    var configs = {
        headers:{
            'Content-Type':'multipart/form-data',
            'X-source': 'web',
            'X-timestamp': timestamp, 
            'X-version': '1.0',
            "X-sign":headerSign, 
        }
    };
    configs.headers.Authorization = (localStorage.cp_userInfo && JSON.parse(localStorage.cp_userInfo).jwt) || '';
    forms.append('file',params.files[0]); 
    let loading = Loading.service({
        lock: true,
        text: '上传中……',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    // setTimeout(()=>{
    //     loading.close();
    // },8000)
    configs.timeout = 15000;
    axios.post(baseURL + url,forms ,configs).then(res=>{
        loading.close(); 
        if(!res.data || res.data.resultCode!=0){
            return Message({
                message: "上传失败",
                type: 'error',
                duration: 1 * 1000
            })
        }
        callback(res)
    }).catch(res=>{
        loading.close(); 
        return Message({
            message: "网络错误,上传失败",
            type: 'error',
            duration: 1 * 1000
        })
    }) 
}
